package com.hmall.search.web;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("search")
public class SearchController {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /*搜索栏自动补全功能*/
    @GetMapping("/suggestion")
    public List<String> suggestion(String key)  {
        try {
            SearchRequest request = new SearchRequest("item");
            request.source()
                    .suggest(new SuggestBuilder().addSuggestion("suggestions", SuggestBuilders
                    .completionSuggestion("suggestion")
                    .prefix(key)
                    .skipDuplicates(true)
                    .size(10)));
            SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Suggest suggest = searchResponse.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }
    /*过滤项聚合功能*/
    @PostMapping("/filters")
    public Map<String, List<String>> filters(@RequestBody RequestParams params){
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(params, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("brand", brandList);
            result.put("category",categoryList);
            // 4.2.根据品牌名称，获取品牌结果
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @PostMapping("/list")
    public PageDTO<Item> list(@RequestBody RequestParams params){

        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(params,request);
            //分页
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            //排序

            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            PageDTO<Item> pageDTO = getItemPageDTO(response);
            return pageDTO;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    private PageDTO<Item> getItemPageDTO(SearchResponse response) {
        SearchHits hits = response.getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] searchHits = hits.getHits();
        PageDTO<Item> pageDTO = new PageDTO<>();
        List<Item> items=new ArrayList<>();
        for (SearchHit hit : searchHits) {
            Item item = getDocumentById(hit.getId());
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && !map.isEmpty()) {
                // 2）根据字段名，获取高亮结果
                HighlightField highlightField = map.get("all");
                if (highlightField != null) {
                    // 3）获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4）把高亮结果放到item中
                    item.setName(hName);
                }
            }
            items.add(item);
        }
        pageDTO.setTotal(value);
        pageDTO.setList(items);
        return pageDTO;
    }


    public Item getDocumentById(String id){
        try {
            GetRequest request = new GetRequest("item", id);
            GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
            String json = response.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            Item item = new Item();
            BeanUtils.copyProperties(itemDoc,item);
            return item;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1.关键字搜索，match查询，放到must中
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            // 不为空，根据关键字查询
            boolQuery.must(QueryBuilders.matchQuery("all", key));
            request.source().highlighter(new HighlightBuilder().field("all").requireFieldMatch(false));
        } else {
            // 为空，查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        // 1.5.价格范围
        Integer minPrice = params.getMinPrice();

        Integer maxPrice = params.getMaxPrice();

        if (minPrice != null && maxPrice != null) {
                long min = minPrice.longValue();
                min = min * 100;
                long max = maxPrice.longValue();
                max = max * 100;
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(min).lte(max));
        }

        // 2.算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery, // 原始查询，boolQuery
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ // function数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), // 过滤条件
                                ScoreFunctionBuilders.weightFactorFunction(10) // 算分函数
                        )
                }
        );

        // 3.设置查询条件
        request.source().query(functionScoreQuery);
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(10)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(10)
        );
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }



}
